package com.sin.j2me.wihd.model;

import org.json.me.JSONException;
import org.json.me.JSONObject;

import com.sin.j2me.framework.NewDebug;
import com.sin.j2me.wihd.common.Protocol;

public class Response {
	public static final int UNKNOWN = 0;
	public static final int OK = 1;
	public static final int FAIL = 2;
	
	private int status;
	private JSONObject response = null;
	
	public Response(String json){
//		System.out.println(json);
		if(json != null && json.length()>0){
			try{
				JSONObject jso = new JSONObject(json);
				if(jso.has(Protocol.R_RESPONSE)){
					this.response = (JSONObject) jso.get(Protocol.R_RESPONSE);
					String st = response.getString(Protocol.R_STATUS); 
					if(st!=null){
						if(st.endsWith(Protocol.R_OK)){
							this.status = OK;
							return;
						}
						else if(st.endsWith(Protocol.R_FAIL)){
							this.status = FAIL;
							return;
						}
					}
				}
			}
			catch(Exception e){
				e.printStackTrace();
			}
		}
		status = UNKNOWN;
	}
	public int getStatus() {
		return status;
	}
	public String toString() {
		return "Response [status=" + status + ", response=" + response + "]";
	}
	public Object get(String key){
		if(this.response.has(key)){
			try {
				return this.response.get(key);
			} catch (JSONException e) {
				e.printStackTrace();
				NewDebug.e(e.getMessage());
			}
		}
		else{
			NewDebug.e("response has no key:" + key);
		}
		return null;
	}
	
	public String getString(String key){
		return (String) get(key);
	}
	
	public boolean isOk(){
		return this.status == OK;
	}
}
